//
//  InstallationImageListViewController.swift
//  ezyform
//
//  Created by MoennigQ on 28/2/19.
//  Copyright © 2019 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import HandyJSON
import RealReachability
import Photos
import PhotosUI
import MBProgressHUD
import SnapKit
import CoreServices
import PDFKit
enum ChecklistFileType: Int{
    case image = 0
    case pdf
}
protocol RefreshPVDDetailChecklistDelegate {
    func refreshPVDDetailChecklist()
    func checkIfHaveReuploadInfo()
}
class InstallationImageListViewController: BaseViewController {
    let topView = ImagesListTopView()
    let tableView = UITableView()
    var model: PVDDetailModel!
    var currentCheckListModel: PVDChecklistModel!
    var localChecklistModel: PVDChecklistModel!
    var delegate: RefreshPVDDetailChecklistDelegate?
    var hideDetailReuploadViewDelegate: HideDetailReuploadViewDelegate?
    var checkListFiles: [CheckListImageDBModel] = [CheckListImageDBModel]()
    let checklistOut = DispatchGroup()
    var tableViewBottomConstraint: Constraint!
    let checkLocationServciceForChecklist: String = "\(APPConfig.loginInfo.currentPVDId!)-Checklist-CheckLocation"
    var checkLocalData: Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
        self.title = "Loading..."
        //获取最新的description和is_show_photos
        InstallationDetailVCHelper.shared().cacheLoadData(model: self.model) {[weak self] in
            guard let strongSelf = self else {return}
            if let data = strongSelf.model.pvd_checklists.first(where: {($0.id ?? 0) == (strongSelf.currentCheckListModel.id ?? 0) }){
                strongSelf.currentCheckListModel = data
                strongSelf.delegate?.refreshPVDDetailChecklist()//考虑两个设备同时操作，需要刷新下最新数据
                strongSelf.refreshData()
                strongSelf.initBottomView()
            }
        } faildClosure: { [weak self] (code, error) in
            guard let strongSelf = self else {return}
            strongSelf.showErrorInfo(code,error)
        }
        //进入Checklist获取一次定位信息
        Tool.shared.requestCurrentLocation()
        NotificationCenter.default.addObserver(self, selector: #selector(refreshChecklistImages(_:)), name: NSNotification.Name(rawValue: "refreshChecklistImages"), object: nil)
    }
    @objc func refreshChecklistImages(_ notification: NSNotification){
        if let dic = notification.userInfo as? NSDictionary, let serverImageModel = dic.object(forKey: "imageModel") as? CheckListImageDBModel, let recordAt = serverImageModel.record_at{
            if let currentImageIndex = self.checkListFiles.firstIndex(where: { iModel in
                let dateStr1 = iModel.record_at ?? ""
                return Tool.shared.compareTwoDateTimeStr(dateStr1, recordAt)
            }){
                self.checkListFiles[currentImageIndex] = serverImageModel
                self.tableView.reloadRows(at: [IndexPath(row: currentImageIndex, section: 0)], with: UITableView.RowAnimation.none)
            }
        }
    }
    func initUI(){
        //top view
        self.view.addSubview(topView)
        topView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //tableview
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.top.equalTo(self.topView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(120)
            self.tableViewBottomConstraint = make.bottom.equalToSuperview().constraint
        }
        //hide seperator line without data
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.tableFooterView = UIView()
        self.tableView.backgroundColor = .white
        self.tableView.register(InstallationImageTableViewCell.self, forCellReuseIdentifier: InstallationImageTableViewCell.reuseCellIdentifier)
        
    }
    
    fileprivate func initBottomView(){
        //(Installing or unqualified) 且当前用户是installer
        if (self.model.job_status == "1" || self.model.job_status == "3") && self.model.isInstallerFlag {
            let bottomViewHeight: CGFloat = 83
            self.tableViewBottomConstraint.update(offset: -bottomViewHeight)
            //bottom
            let bottomView = UIView()
            bottomView.backgroundColor = UIColor.white
            self.view.addSubview(bottomView)
            bottomView.snp.makeConstraints { (make) in
                make.left.bottom.right.equalToSuperview()
                make.height.equalTo(bottomViewHeight)
            }
            
            //
            var btnSize = CGSize(width: 164, height: 64)
            if self.currentCheckListModel.id == ChecklistFixedId.certificateOfElectricalSafety.rawValue {//certificate of Electrical safety 显示三个菜单
                let addAttachmentBtn = UIButton()
                addAttachmentBtn.setImage(UIImage(named: "installation_detail_checklist_imagelist_add_attachment_icon"), for: UIControl.State.normal)
                bottomView.addSubview(addAttachmentBtn)
                addAttachmentBtn.snp.makeConstraints { (make) in
                    make.top.equalToSuperview().offset(7)
                    make.centerX.equalToSuperview()
                    make.size.equalTo(btnSize)
                }
                addAttachmentBtn.addTarget(self, action: #selector(addAttachmentBtnClick), for: UIControl.Event.touchUpInside)
            }else {
                if let showPhotos = self.currentCheckListModel.is_show_photos, showPhotos{//显示拍照，选择相册的按钮
                    let totalInternal: CGFloat = 40
                    if APPConfig.WidthForPortrait < (btnSize.width * 2 + totalInternal) {
                        btnSize.width = (APPConfig.WidthForPortrait - totalInternal) / 2
                        btnSize.height = btnSize.width / 164 * 64
                    }
                    let btnMargin: CGFloat = APPConfig.WidthForPortrait / 2 - 10 - btnSize.width
                    //take phots
                    let takePhotoBtn = UIButton()
                    takePhotoBtn.setImage(UIImage(named: "installation_detail_checklist_imagelist_takephoto_icon"), for: UIControl.State.normal)
                    bottomView.addSubview(takePhotoBtn)
                    takePhotoBtn.snp.makeConstraints { (make) in
                        make.top.equalToSuperview().offset(7)
                        make.left.equalToSuperview().offset(btnMargin)
                        make.size.equalTo(btnSize)
                    }
                    
                    //select photos from library
                    let selectFromLibraryBtn = UIButton()
                    selectFromLibraryBtn.setImage(UIImage(named: "installation_detail_checklist_imagelist_library_icon"), for: UIControl.State.normal)
                    bottomView.addSubview(selectFromLibraryBtn)
                    selectFromLibraryBtn.snp.makeConstraints { (make) in
                        make.top.equalToSuperview().offset(7)
                        make.right.equalToSuperview().offset(-btnMargin)
                        make.size.equalTo(btnSize)
                    }
                    selectFromLibraryBtn.addTarget(self, action: #selector(selectFromPhotosLibrary), for: UIControl.Event.touchUpInside)
                    
                    takePhotoBtn.addTarget(self, action: #selector(takePhoto), for: UIControl.Event.touchUpInside)
                }else{//只显示拍照按钮，不显示选择相册的按钮
                    //take phots
                    let takePhotoBtn = UIButton()
                    takePhotoBtn.setImage(UIImage(named: "installation_detail_checklist_imagelist_takephoto_icon"), for: UIControl.State.normal)
                    bottomView.addSubview(takePhotoBtn)
                    takePhotoBtn.snp.makeConstraints { (make) in
                        make.top.equalToSuperview().offset(7)
                        make.centerX.equalToSuperview()
                        make.size.equalTo(btnSize)
                    }
                    takePhotoBtn.addTarget(self, action: #selector(takePhoto), for: UIControl.Event.touchUpInside)
                }
            }
            
            //电工表单模板不为空，且当前checklist中的actions中的electrical 是true
            if let electricalTemplate = self.model.electrical_template,let checklistModel = self.currentCheckListModel, let actions = checklistModel.actions, let electricalFlag = actions.electrical, electricalTemplate != "" && electricalFlag{
                let btn1 = UIButton(type: .custom)
                btn1.frame = CGRect(x: 0, y: 0, width: 30, height: 24)
                btn1.setImage(UIImage(named: "installation_detail_checklist_imagelist_electrical_icon"), for: .normal)
                btn1.addTarget(self, action: #selector(addElectricialCertificate), for: .touchUpInside)
                let item1 = UIBarButtonItem(customView: btn1)
                self.navigationItem.setRightBarButtonItems([item1], animated: true)
            }
        }else{
            self.tableViewBottomConstraint.update(offset: 0)
        }
    }
    fileprivate func getChecklistModelById(_ newModel: PVDDetailModel)->PVDChecklistModel?{
        guard let _ = self.currentCheckListModel else{
            return nil
        }
        guard let currentChecklistId = self.currentCheckListModel.id else{
            return nil
        }
        for tempCheckModel in newModel.pvd_checklists {
            if let id = tempCheckModel.id, id == currentChecklistId{
                return tempCheckModel
            }
        }
        return nil
    }
    fileprivate func refreshData() {
        guard let newChecklistModel = self.getChecklistModelById(self.model) else{
            return
        }
        self.currentCheckListModel = newChecklistModel
        //1.初始化
        var serverImages = [CheckListImageDBModel]()
        var localAddImages = [CheckListImageDBModel]()
        var localDeletedImages = [CheckListImageDBModel]()
        
        self.title = self.currentCheckListModel.title
        //1.set top data
        topView.setData(self.currentCheckListModel)
        //2.get local checklist
        self.model.checkListModifyFlag = false
        localChecklistModel = DBManager.shared.loadChecklistDataByChecklistId(pvdId: self.model.id, checklistId: self.currentCheckListModel.id!)
        localAddImages = self.localChecklistModel.localAddImages
        //2.检查如果本地已经上传，就删除本地数据
        if localAddImages.count > 0{
            _ = localAddImages.map { localImageModel in
                _ = self.currentCheckListModel.images.map { serverImageModel in
                    if localImageModel.record_at == serverImageModel.record_at {
                        DBManager.shared.deleteChecklistImageData(model: localImageModel)
                    }
                }
            }
        }
        //3.再次获取本地数据
        localChecklistModel = DBManager.shared.loadChecklistDataByChecklistId(pvdId: self.model.id, checklistId: self.currentCheckListModel.id!)
        localDeletedImages = self.localChecklistModel.localDeletedImages
        localAddImages = self.localChecklistModel.localAddImages
        //4.有删除数据，或本地增加的数据就说明有本地数据
        if localDeletedImages.count > 0 || localAddImages.count > 0 {
            self.model.checkListModifyFlag = true
        }
        
        //5.检查是否有删除服务器数据的本地数据
        for dic in self.currentCheckListModel.images {
            let imageId = dic.id!
            var deletedFlag: Bool = false
            if localDeletedImages.count > 0{
                for localDic in localDeletedImages {
                    let localImageId = localDic.id!
                    if localImageId == imageId {
                        deletedFlag = true
                    }
                }
            }
            if !deletedFlag {
                serverImages.append(dic)
            }
        }
        self.checkListFiles = serverImages + localAddImages
        self.tableView.reloadData()
    }
    @objc func addElectricialCertificate(){
        let vc = ElectricalCertificateViewController()
        vc.delegate = self
        vc.model = self.model//不能去掉，否则Add ESC后，image list中的数据丢失
        vc.currentCheckListModel = self.currentCheckListModel
        self.navigationController?.pushViewController(vc, animated: false)
    }
    @objc func takePhoto(){
        if let lodgedCheck = self.currentCheckListModel.lodged_check, lodgedCheck{//需要GPS定位信息，友好提示，但是不强制
            let checkChecklistFlag = UserDefaults.standard.value(forKey: checkLocationServciceForChecklist) as? Bool ?? false
            if checkChecklistFlag {//弹出提示过就不再提示
                self.openTakePhotoVC()
            }else{//没提示过，检查需要什么提示
                if CLLocationManager.locationServicesEnabled() == false {//设备未开启GPS功能
                    self.showRequstGPSAlertView()
                }else {//设备已开启GPS功能
                    let status = CLLocationManager.authorizationStatus()
                    if status == .denied || status == .restricted {
                        self.showRequstGPSAlertView()
                    }else{
                        self.openTakePhotoVC()
                    }
                }
            }
        }else{
            self.openTakePhotoVC()
        }
    }
    @objc func addAttachmentBtnClick(){
        let cellList = [CellModel(title: "Take Photo"),
                        CellModel(title: "Choose From Library"),
                        CellModel(title: "Upload Files (PDF)")]
        let actionSheetView = CustomActionSheet(aHeadView: UIView(), aCellArray: cellList, aCancelModel: CellModel(title: "Cancel"), aSelectedClosure: { [weak self](row) in
            guard let strongSelf = self else {return}
            if row == 0 {//Take Photo
                strongSelf.takePhoto()
            }else if row == 1{//Choose From Library
                strongSelf.selectFromPhotosLibrary()
            }else if row == 2 {//Upload Files (PDF)
                if #available(iOS 14.0, *) {
                    let vc = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.pdf])
                    vc.allowsMultipleSelection = false//不允许多选
                    vc.delegate = strongSelf
                    vc.modalPresentationStyle = .overFullScreen
                    strongSelf.navigationController?.present(vc, animated: true, completion: nil)
                } else {
                    let vc = UIDocumentPickerViewController(documentTypes: [kUTTypePDF as String], in: UIDocumentPickerMode.import)
                    vc.allowsMultipleSelection = false//不允许多选
                    vc.delegate = strongSelf
                    vc.modalPresentationStyle = .overFullScreen
                    strongSelf.navigationController?.present(vc, animated: true, completion: nil)
                }
                
            }
        }, aCancelClosure: nil)
        self.navigationController?.view.addSubview(actionSheetView)
    }
    func openTakePhotoVC(){
        //只有这三个才做提示
        if self.currentCheckListModel.is_selfie_flag {
            InstallationDetailVCHelper.shared().checkOrderChecklist(vc: self, model: self.model, checklistModel: self.currentCheckListModel) {
                self.toTakePhtoVC()
            }
        }else{
            toTakePhtoVC()
        }
    }
    func toTakePhtoVC(){
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (status) in
            DispatchQueue.main.async {
                if status {
                    let vc = InstallationTakePhotoViewController()
                    vc.delegate = self
                    vc.model = self.model
                    vc.currentCheckListModel = self.currentCheckListModel
                    vc.photosCnt = self.checkListFiles.count
                    vc.modalPresentationStyle = .overFullScreen
                    self.present(vc, animated: true, completion: nil)
                    
                }else{
                    self.alertViewWithMsg(message: NSLocalizedString("camera.permission", comment: ""))
                }
            }
        }
    }
    func showRequstGPSAlertView(){
        let view = ChecklistRequestGPSAlertView()
        view.settingsBtnClosure = {
            //URL(string:"App-Prefs:root=Privacy&path=LOCATION")是私有API, 不能使用，审核会被拒的
            if  UIApplication.shared.canOpenURL(URL(string: UIApplication.openSettingsURLString)!) {
                UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:],completionHandler: nil)
            }
            self.saveRequestGPSAlertStatus(view.checkBtn.tag)
        }
        view.okBtnClosure = {
            self.saveRequestGPSAlertStatus(view.checkBtn.tag)
            self.openTakePhotoVC()
        }
        view.moreInfoBtnClosure = {
            let vc = AttachmentViewController()
            vc.attchmentType = .OtherLink
            vc.attachmentURL = "http://www.cleanenergyregulator.gov.au/About/Pages/News%20and%20updates/NewsItem.aspx?ListId=19b4efbb-6f5d-4637-94c4-121c1f96fcfe&ItemId=915"
            vc.attachmentTitle = "GreenDeal"
            self.navigationController?.pushViewController(vc, animated: false)
        }
        self.view.addSubview(view)
        view.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    func saveRequestGPSAlertStatus(_ tag: Int )  {
        if tag == 1 {
            UserDefaults.standard.set(true, forKey: checkLocationServciceForChecklist)
        }
    }
    //upload checklist without uploading view
    fileprivate func uploadCheckList(_ imageModel: CheckListImageDBModel, operateFlag: String,fileType: ChecklistFileType = .image){
        if model.checkListModifyFlag {
            if Connectivity.isConnectedToInternet  {
                //隐藏Detail的ReuploadView
                self.hideDetailReuploadViewDelegate?.hideDetailReuploadView()
                self.refreshData()
                self.delegate?.refreshPVDDetailChecklist()
                UploadManager.shared().uploadChecklistImage(pvdId: self.model.id, currentCheckListModel: self.currentCheckListModel, imageModel: imageModel,operFlag: operateFlag,fileType: fileType)
            }else{
                self.refreshImageslist(true)
            }
        }
    }
    @objc func selectFromPhotosLibrary(){
        if #available(iOS 14, *) {//iOS 14之后的相册选择（包括14）
            let level = PHAccessLevel.readWrite
            PHPhotoLibrary.requestAuthorization(for: level){ (status) in
                DispatchQueue.main.async {
                    if status == .authorized {//全部相片
                        var configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
                        configuration.filter = .images
                        configuration.selectionLimit = 10//最多选择10个
                        let picker = PHPickerViewController(configuration: configuration)
                        picker.delegate = self
                        picker.modalPresentationStyle = .overFullScreen
                        self.present(picker, animated: true)
                    }else if status == .limited{//部分相片
                        self.selectFromPhotosLibraryBefore()
                    }else {//无权限
                        self.alertViewWithMsg(message: NSLocalizedString("photos.permission", comment: ""))
                        return
                    }
                }
            }
        }else{//14以前的
            PHPhotoLibrary.requestAuthorization({ (status) in
                DispatchQueue.main.async {
                    if status == .authorized {//有权限
                        self.selectFromPhotosLibraryBefore()
                    }else{//无权限
                        self.alertViewWithMsg(message: NSLocalizedString("photos.permission", comment: ""))
                        return
                    }
                }
            })
        }
    }
    //自定义相册
    fileprivate func selectFromPhotosLibraryBefore(){
        _ = self.presentHGImagePicker(maxSelected: 10) { (assets) in
            
            if assets.count > 0 {
                if self.currentCheckListModel.images.count <= 0 {
                    self.currentCheckListModel.answered_at = Tool.shared.getCurrentDatetime()
                }
                for i in 0  ..< assets.count {
                    self.addImageFromPhotos(assets[i])
                }
                self.delegate?.refreshPVDDetailChecklist()
            }
        }
        
    }
    private func getPhotoModelFromAssert(_ assert: PHAsset)->ChecklistPhotoModel{
        var photoModel = ChecklistPhotoModel()
        if let data = assert.creationDate{
            photoModel.createdAt = Tool.shared.getDatetimeStr(data)
        }
        if let data = assert.location?.coordinate.longitude{
            photoModel.longitude = "\(data)"
        }
        if let data = assert.location?.coordinate.latitude{
            photoModel.latitude = "\(data)"
        }
        return photoModel
    }
    fileprivate func addImageFromPhotos(_ assert: PHAsset){
        let photoModel = self.getPhotoModelFromAssert(assert)
        
        var resultData: NSData?
        let lodgedCheck = self.currentCheckListModel.lodged_check ?? false
        if lodgedCheck  {//true上传原图
            Tool.shared.getOrignalImageDataOfPHAsset(asset: assert) { nsdata in
//                let sourceNew = CGImageSourceCreateWithData(nsdata as CFData, nil)!
//                let metadataNew = CGImageSourceCopyPropertiesAtIndex(sourceNew, 0, nil) as? [AnyHashable: Any]
                let data = (nsdata as Data)
                if  data.getImageFormat() == .HEIC{
                    guard let originImage = Tool.shared.getUIImage(asset: assert) else{return}
                    resultData = Tool.shared.resetSizeOfImageData(source_image: originImage)
                    self.saveImageData(resultData, photoModel: photoModel)
                }else{
                    self.saveImageData(nsdata, photoModel: photoModel)
                }
                
            }
        }else{//false压缩图片，
            guard let originImage = Tool.shared.getUIImage(asset: assert) else{return}
            resultData = Tool.shared.resetSizeOfImageData(source_image: originImage)
            self.saveImageData(resultData, photoModel: photoModel)
        }
        
    }
    fileprivate func saveImageData(_ resultData: NSData?, photoModel: ChecklistPhotoModel,fileType: ChecklistFileType = .image){
        guard let originImageData = resultData else{return}
        let fileName = Tool.shared.getCurrentDatetimeTamp()
        //checklist image
        
        var imagePath = ""
        if fileType == .image {
            imagePath = Tool.shared.getChecklistImagePath(fileName,fileSuffix: APPConfig.ImageSuffix)
        }else{
            imagePath = Tool.shared.getChecklistImagePath(fileName,fileSuffix: APPConfig.PDFSuffix)
        }
        do {
            try originImageData.write(to: URL(fileURLWithPath: imagePath), options: [.atomic])
            
            let imageModel = CheckListImageDBModel()
            imageModel.pvd_id = self.model.id
            imageModel.checklist_id = self.currentCheckListModel.id!
            imageModel.record_at = Tool.shared.getCurrentDatetime()
            imageModel.photo_source = "photo_album"//图片来源于相册
            imageModel.photo_created_at = photoModel.createdAt
            imageModel.latitude = photoModel.latitude
            imageModel.longitude = photoModel.longitude
            imageModel.image = imagePath
            imageModel.id = fileName
            imageModel.title = self.currentCheckListModel.title
            //add local image
            DBManager.shared.insertChecklistImages(model: imageModel)
            self.refreshImageslist(false)//只刷新当前界面的list和Detail中的checklist数据，上传数据前不显示Reupload，上传完或无网才显示Reupload
            self.uploadCheckList(imageModel,operateFlag: "ADD",fileType: fileType)
        }catch{
            NSLog("Saving checklist image to local failed")
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
        Tool.shared.printDebug("InstallationImageListViewController deinit")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        Tool.shared.printDebug("\(self) didReceiveMemoryWarning")
        // Dispose of any resources that can be recreated.
    }
}
extension InstallationImageListViewController: UITableViewDataSource,UITableViewDelegate,RefreshPVDImageslistDelegate{
    
    //refresh delegate
    func refreshImageslist(_ refreshDetailFlag: Bool) {
        self.refreshData()
        self.delegate?.refreshPVDDetailChecklist()
        if refreshDetailFlag {
            self.delegate?.checkIfHaveReuploadInfo()
        }
    }
    func uploadImages(_ imageModel: CheckListImageDBModel, _ operateFlag: String) {
        self.refreshData()
        self.uploadCheckList(imageModel, operateFlag: operateFlag)
    }
    //Table Data source
    func numberOfSections(in tableView: UITableView) -> Int{
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.checkListFiles.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    //implement protocal of UITableViewDataSource:editing style
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell : InstallationImageTableViewCell! = tableView.dequeueReusableCell(withIdentifier: InstallationImageTableViewCell.reuseCellIdentifier) as? InstallationImageTableViewCell
        if (cell == nil){
            cell = InstallationImageTableViewCell(style: .default, reuseIdentifier: InstallationImageTableViewCell.reuseCellIdentifier)
        }
        let iModel = self.checkListFiles[indexPath.row]
        cell!.setData(iModel,indexPath.row + 1)
        return cell
    }
    
    //implement protocal of UITableViewDataSource:whether or not edit one row
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool{
        return true
    }
    //implement protocal of UITableViewDataSource:editing style
    internal func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle{
        //(installing or unqualified) 且当前用户是installer才能删除
        if (self.model.job_status == "1"  || self.model.job_status == "3") && self.model.isInstallerFlag{
            if self.currentCheckListModel.is_selfie_flag{//
                return UITableViewCell.EditingStyle.none
            }
            return UITableViewCell.EditingStyle.delete
        }else{
            return UITableViewCell.EditingStyle.none
        }
    }
    //implement protocal of UITableViewDataSource:
    internal func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath){
        if editingStyle == UITableViewCell.EditingStyle.delete {
            //delete server image
            let model = self.checkListFiles[indexPath.row]
            let imagePath = model.image ?? ""
            let pdfFlag = imagePath.contains(APPConfig.PDFSuffix)
            let alertVC = UIAlertController(title: "Delete \(pdfFlag ? "File" : "Image")" , message: "Are you sure to delete this \(pdfFlag ? "file" : "image")?", preferredStyle: UIAlertController.Style.alert)
            let noAction = UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: { (_) in
                self.dismiss(animated: true, completion: nil)
            })
            
            let okAction = UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: { (_) in
                
                if imagePath.contains("http"){//server
                    model.pvd_id = self.model.id
                    model.checklist_id = self.currentCheckListModel.id
                    model.title = self.title
                    DBManager.shared.insertChecklistImages(model: model)
                    self.refreshImageslist(false)
                    self.uploadCheckList(model,operateFlag: "DEL")
                }else{
                    //delete local add image
                    DBManager.shared.deleteChecklistImageData(model: model)
                    self.refreshImageslist(true)
                }
                //show deleted toast
                MBProgressHUD.showToast(parentView: self.view, text: "\(pdfFlag ? "File" : "Image") deleted successfully")
            })
            alertVC.addAction(noAction)
            alertVC.addAction(okAction)
            self.present(alertVC, animated: true, completion: nil)
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let iModel: CheckListImageDBModel = self.checkListFiles[indexPath.row]
        let imagePath = iModel.image ?? ""
        if imagePath.contains(APPConfig.PDFSuffix){
            let vc = AttachmentViewController()
            vc.attchmentType = .ChecklistPDF
            vc.attachmentURL = imagePath
            vc.attachmentTitle = ""
            self.navigationController?.pushViewController(vc, animated: false)
        }else{
            let (imagesList, index) = self.getAllImagePathAndIndex(iModel)
            if imagesList.count > 0 {
                let vc = CommonBrowseImageViewController()
                vc.imagesArray = imagesList
                vc.currentIndex = index
                self.navigationController?.pushViewController(vc,animated: false)
            }
        }
    }
    //MARK: - 获取所有的Image类型（过滤掉pdf），及当前选择行的index
    private func getAllImagePathAndIndex(_ selImageModel: CheckListImageDBModel)->(Array<CheckListImageDBModel>, Int){
        //1.过滤出来所有的图片，不要pdf
        let resultList = self.checkListFiles.filter { iModel in
            if let pathStr = iModel.image, !pathStr.contains(APPConfig.PDFSuffix){
                return true
            }else{
                return false
            }
        }
        //2.获取当前过滤掉pdf的index
        let index = resultList.firstIndex {  iModel in
            if let pathStr = iModel.image,let selPathStr = selImageModel.image, pathStr == selPathStr{
                return true
            }else{
                return false
            }
        }
        
        return (resultList, index ?? 0)
    }
}
extension InstallationImageListViewController: PHPickerViewControllerDelegate{
    //MARK: - iOS 14以后，从相册选择图片回调
    @available(iOS 14, *)
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true) {//代码必需加到回调中，防止选图片界面dismiss反应慢，导致Add可以点击多次导致增加n多图片
            guard results.count > 0 else {
                return
            }
            if self.currentCheckListModel.images.count <= 0 {
                self.currentCheckListModel.answered_at = Tool.shared.getCurrentDatetime()
            }
            for result in results {
                if let assetId = result.assetIdentifier,
                   let asset = PHAsset.fetchAssets(withLocalIdentifiers: [assetId], options: nil).firstObject
                {
                    self.addImageFromPhotos(asset)
                }
            }
        }
    }
}
extension InstallationImageListViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let firstUrl = urls.first else {return}
        //startAccessingSecurityScopedResource()返回true的话，和stopAccessingSecurityScopedResource成对出现
        let urlAuthrized = firstUrl.startAccessingSecurityScopedResource()
        //获取授权
        //通过文件协调器读取文件地址
        var fileData: Data?
        let fileCoordinator = NSFileCoordinator()
        fileCoordinator.coordinate(readingItemAt: firstUrl, options: [.withoutChanges], error: nil) { (newUrl) in
            let fileName = newUrl.lastPathComponent
            print("fileName \(fileName)")
            //读取文件协调器提供的新地址里的数据
            fileData = try? Data.init(contentsOf: newUrl, options: [.mappedIfSafe])
            if let data = fileData {
                self.saveImageData(data as NSData, photoModel: ChecklistPhotoModel(),fileType: .pdf)
                //获取到数据
//                if let img = self.pdfThumbnail(newUrl), let data = img.jpegData(compressionQuality: 0.5){
//                    self.saveImageData(data as NSData, photoModel: ChecklistPhotoModel())
//                }
            }
        }
        //
        if urlAuthrized {
            firstUrl.stopAccessingSecurityScopedResource()
        }
    }
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        self.dismiss(animated: true)
    }
    // MARK: - 将PDF转换成图片（暂时没有用，直接上传PDF文件，不用转换了）
    private func pdfThumbnail(_ url: URL)->UIImage? {
//            guard let path = Bundle.main.path(forResource: "Android开发工程师-许亮-拉勾招聘", ofType: "pdf") else { return nil}
//            let url = URL(fileURLWithPath: path)
        guard let data = try? Data(contentsOf: url),let pdfDoc = PDFDocument(data: data),
              let page = pdfDoc.page(at: 0) else {
            return nil
        }
        let pageCount = pdfDoc.pageCount
        let pageSize = page.bounds(for: .mediaBox)
        let pdfScale = 2.0// / pageSize.width// Apply if you're displaying the thumbnail on screen
        let scale = UIScreen.main.scale * pdfScale
        let screenSize = CGSize(width: pageSize.width * scale,
                                height: pageSize.height * scale)
        //画布size
        let size = CGSize(width: screenSize.width, height: screenSize.height * CGFloat(pageCount))
        UIGraphicsBeginImageContextWithOptions(size, false, 1.0)
        for index in 0..<pageCount {
            if let tempPage = pdfDoc.page(at: index){
                let img = tempPage.thumbnail(of: screenSize, for: .mediaBox)
                img.draw(in: CGRect(x: 0, y: CGFloat(index) * screenSize.height, width: screenSize.width, height: screenSize.height))
            }
        }
        let combineImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return combineImage
    }
}

